package com.ruoyi.web.core.mybatis.driver;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.web.core.mybatis.anno.SimpleID;
import com.ruoyi.web.core.mybatis.anno.SimpleIgnore;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Insert
 */
@Slf4j
public class SimpleInsertDriver extends XMLLanguageDriver implements LanguageDriver {

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
        String tableName = StrUtil.toUnderlineCase(parameterType.getSimpleName()).toLowerCase();
        Field[] fields = parameterType.getDeclaredFields();
        List<String> colList = new ArrayList<>();
        colList.add(" <trim suffixOverrides=\",\"> ");
        List<String> valList = new ArrayList<>();
        valList.add(" <trim suffixOverrides=\",\"> ");
        Arrays.stream(fields)
                .filter(f -> {
                    if (f.isAnnotationPresent(SimpleID.class)) {
                        return !f.getAnnotation(SimpleID.class).auto();
                    }
                    return !f.isAnnotationPresent(SimpleIgnore.class);
                })
                .forEach(f -> {
                    String fn = f.getName();
                    String cn = StrUtil.toUnderlineCase(fn).toLowerCase();
                    colList.add("<if test=\"" + fn + " != null\"> " + cn + ",</if>");
                    valList.add("<if test=\"" + fn + " != null\"> #{" + fn + "},</if>");
                });
        colList.add(" </trim> ");
        valList.add(" </trim> ");

        String sql = " insert into " + tableName + " ( " +
                String.join("\n", colList) +
                " ) values ( " +
                String.join("\n", valList) +
                " ) ";
        script = "<script>" + sql + "</script>";
        return super.createSqlSource(configuration, script, parameterType);
    }
}
